#include"stack.h"

void StackInit(Stack* ps)
{
	assert(ps);

	ps->a = (STDataType*)malloc(sizeof(STDataType) * 4);
	if (ps->a == NULL)
	{
		perror("malloc fail");
		exit(-1);
	}
	ps->capacity = 4;
	ps->top = -1;

}

void StackDestroy(Stack* ps)
{
	assert(ps);

	ps->capacity = 0;
	ps->top = -1;
	free(ps->a);
}

void StackPush(Stack* ps, STDataType data)
{
	assert(ps);

	if (ps->top + 1 == ps->capacity)
	{
		STDataType* tmp = (STDataType*)realloc(ps->a, ps->capacity * 2 * sizeof(STDataType));
		if (tmp == NULL)
		{
			perror("realloc fail");
			exit(-1);
		}
		ps->a = tmp;
		ps->capacity *= 2;
	}


	ps->top++;
	ps->a[ps->top] = data;
}

void StackPrint(Stack* ps)
{
	assert(ps);

	int i = 0;
	for (i = 0; i < ps->top + 1; i++)
	{
		printf("%d ", ps->a[i]);
	}
}

void StackPop(Stack* ps)
{
	assert(ps);
	assert(ps->top > -1);

	ps->top--;
}

STDataType StackTop(Stack* ps)
{
	assert(ps);

	return ps->a[ps->top];
}

int StackSize(Stack* ps)
{
	assert(ps);

	return ps->top + 1;
}

int StackEmpty(Stack* ps)
{
	assert(ps);

	return ps->top == -1;
}


